﻿using System;
using System.Threading;

namespace Event.MemoryLeak
{
    public class EventPublisher
    {
        public static int Count;

        public event EventHandler<PublisherEventArgs> OnSomething;

        public EventPublisher()
        {
            Interlocked.Increment(ref Count);
        }

        public void TriggerSomething()
        {
            RaiseOnSomething(new PublisherEventArgs(Count));
        }

        protected void RaiseOnSomething(PublisherEventArgs e)
        {
            EventHandler<PublisherEventArgs> handler = OnSomething;
            if (handler != null) handler(this, e);
        }

        ~EventPublisher()
        {
            Interlocked.Decrement(ref Count);
        }
    }

    public class PublisherEventArgs : EventArgs
    {
        public int PublisherReferenceCount { get; private set; }

        public PublisherEventArgs(int publisherReferenceCount)
        {
            PublisherReferenceCount = publisherReferenceCount;
        }
    }
}